#_*_coding:utf8_*_
from urllib import request, parse

from django.conf import settings

import json
import ssl
ssl._create_default_https_context = ssl._create_unverified_context 
import pymysql
import os
import time

class SaltAPI(object):
    __token_id = ''
    def __init__(self,*args,**kwargs):
        self.__url = settings.SALT_API_URL.rstrip("/")
        self.__user = settings.SALT_API_USER
        self.__password = settings.SALT_API_PASSWD


    def token_id(self):
        ''' user login and get token id '''
        params = {'eauth': 'pam', 'username': self.__user, 'password': self.__password}
        obj = parse.urlencode(params).encode('utf-8')

        content = self.postRequest(obj,prefix='/login')
        try:
            self.__token_id = content['return'][0]['token']
        except KeyError:
            raise KeyError
    def postRequest(self,obj,prefix='/'):
        url = self.__url + prefix
        headers = {'X-Auth-Token'   : self.__token_id}
        req = request.Request(url, obj, headers)
        opener = request.urlopen(req)
        content = json.loads(opener.read().decode('utf8'))
        return content


    def list_all_key(self):
        params = {'client': 'wheel', 'fun': 'key.list_all'}
        obj = parse.urlencode(params).encode('utf-8')
        self.token_id()
        content = self.postRequest(obj)
        minions = content['return'][0]['data']['return']['minions']
        minions_pre = content['return'][0]['data']['return']['minions_pre']
        return minions,minions_pre
    def delete_key(self,node_name):
        params = {'client': 'wheel', 'fun': 'key.delete', 'match': node_name}
        obj = parse.urlencode(params).encode('utf-8')
        self.token_id()
        content = self.postRequest(obj)
        ret = content['return']#[0]['data']['success']
        return ret
    def accept_key(self,node_name):
        params = {'client': 'wheel', 'fun': 'key.accept', 'match': node_name}
        obj = parse.urlencode(params).encode('utf-8')
        self.token_id()
        content = self.postRequest(obj)
        ret = content['return']#[0]['data']['success']
        return ret
    def remote_noarg_execution(self,tgt,fun):
        ''' Execute commands without parameters '''
        params = {'client': 'local', 'tgt': tgt, 'fun': fun}
        obj =parse.urlencode(params).encode('utf-8')
        self.token_id()
        content = self.postRequest(obj)
        ret = content['return'][0] #['monitor']['cpu_model']
        return ret
    def remote_execution(self,tgt,fun,arg):
        ''' Command execution with parameters '''        
        params = {'client': 'local', 'tgt': tgt, 'fun': fun, 'arg': arg}
        obj = parse.urlencode(params).encode('utf-8')
        self.token_id()
        content = self.postRequest(obj)
        print('content:%s' %content)
        ret = content['return'][0][tgt]
        return ret




        #self.__cursor.close()
        #self.__mysql_connect.close()





    def get_remote_execution_from_jid(self,jid):
        params = {'client': 'runner', 'fun': 'jobs.lookup_jid', 'jid': jid}
        obj = parse.urlencode(params).encode('utf-8')
        self.token_id()
        content = self.postRequest(obj)
        print('content:%s' % content)
        ret = content['return'][0]
        return ret



    def target_remote_execution(self,tgt,fun,arg):
        ''' Use targeting for remote execution '''
        #params = {'client': 'local', 'tgt': tgt, 'fun': fun, 'arg': arg, 'expr_form': 'nodegroup'}
        params = {'client': 'local', 'tgt': tgt, 'fun': fun, 'arg': arg , 'expr_form': 'nodegroup'}
        obj = parse.urlencode(params).encode('utf-8')
        self.token_id()
        content = self.postRequest(obj)
        print('content:%s' % content)
        jid = content['return'][0]['jid']
        return jid
    def deploy(self,tgt,arg):
        ''' Module deployment '''
        params = {'client': 'local', 'tgt': tgt, 'fun': 'state.sls', 'arg': arg}
        obj = parse.urlencode(params).encode('utf-8')
        self.token_id()
        content = self.postRequest(obj)
        return content
    def async_deploy(self,tgt,arg):
        ''' Asynchronously send a command to connected minions '''
        params = {'client': 'local_async', 'tgt': tgt, 'fun': 'state.sls', 'arg': arg}
        obj = parse.urlencode(params).encode('utf-8')
        self.token_id()
        content = self.postRequest(obj)
        jid = content['return'][0]['jid']
        return jid
    def target_deploy(self,tgt,arg):
        ''' Based on the node group forms deployment '''
        params = {'client': 'local_async', 'tgt': tgt, 'fun': 'state.sls', 'arg': arg, 'expr_form': 'nodegroup'}
        obj = parse.urlencode(params).encode('utf-8')
        self.token_id()
        content = self.postRequest(obj)
        jid = content['return'][0]['jid']
        return jid


def main():
    sapi = SaltAPI(url='https://192.168.10.205:8888',username='xiaoluo',password='123456')
    print(sapi.list_all_key())
    #sapi.delete_key('test-01')
    print(sapi.accept_key('localhost'))
    #sapi.deploy('test-01','nginx')
    print(sapi.remote_noarg_execution('*','grains.items'))


if __name__ == '__main__':
    main()
